<script setup name="SysUserIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import FormMode from "./modules/FormMode/index.vue";
import { delUser, listUser, resetUserPwd } from "@/api/system/user";
import { parseTime } from "@/utils/aidex";
import { listDeptTree } from "@/api/system/dept";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();
// const route = useRoute()

const data = ref({
  loading: false,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: "",
    name: ""
  },
  // 搜索
  search: {
    name: "",
    deptId: "",
    userType: "0"
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],
  colorList: ["#F38709", "#813AFD", "#00C4AA", "#4B7AEE"],
  // 部门树 列表
  deptOptions: [],
  expandedKeys: []
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
  // 获取部门树
  getTreeselect();
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});
// 选取随机颜色
function getRandomColor(index) {
  return data.value.colorList[index % 4];
}
// 截取用户名称
function getShowName(name) {
  if (name.length > 2) {
    name = name.substring(name.length - 2);
  }
  return name;
}
// 部门树
function getTreeselect() {
  listDeptTree("0", 3).then((response) => {
    data.value.deptOptions = response.data;
    getExpandedKeys(data.value.deptOptions, 3);
  });
}
function getExpandedKeys(nodes, expandLevel) {
  if (expandLevel > 1) {
    // 最后一层不展开
    if (nodes != null) {
      nodes.forEach((node) => {
        data.value.expandedKeys.push(node.id);
        expandLevel = expandLevel - 1;
        return getExpandedKeys(node.children, expandLevel);
      });
    }
  }
}
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.name && (params.name = data.value.search.name);
  data.value.search.deptId && (params.deptId = data.value.search.deptId);
  data.value.search.userType && (params.userType = data.value.search.userType);

  console.log("params", params);
  listUser(params).then((res) => {
    data.value.loading = false;
    data.value.dataList = res.data.list;
    pagination.value.total = res.data.total;
  });
}

// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
//  获取树选项节点
function getnode(node, prop, event) {
  console.log("node", node, prop, event);
  data.value.search.deptId = node.id;
}
function onCreate() {
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName"
    });
  } else {
    data.value.formModeProps.id = "";
    data.value.formModeProps.visible = true;
  }
}

function onEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.formModeProps.id = row.id;
    data.value.formModeProps.name = row.name;
    data.value.formModeProps.visible = true;
  }
}
function onAdd() {
  data.value.formModeProps.id = "";
  data.value.formMode = "dialog";
  data.value.formModeProps.visible = true;
}
// 批量删除 单独删除
function onDel(row) {
  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });
  const names =
    row.name ||
    data.value.batch.selectionDataList.map((item) => {
      return item.name;
    });
  if (ids.length > 0) {
    ElMessageBox.confirm(`确认删除「${names}」吗？`, "确认信息")
      .then(() => {
        delUser(ids).then((res) => {
          getDataList();
          if (res.code == 200)
            ElMessage.success({
              message: "删除成功",
              center: true
            });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择数据", center: true });
  }
}
const activeName = ref("first");

const handleClick = (tab, event) => {
  if (tab.paneName == "second") {
    data.value.search.userType = "1";
    getDataList();
  } else {
    data.value.search.userType = "0";
    getDataList();
  }
};
function resetPwd(row) {
  ElMessageBox.confirm(`确认要重置密码吗（默认密码：123456）？`, "确认信息")
    .then(() => {
      resetUserPwd(row.id, "123456").then((res) => {
        getDataList();
        if (res.code == 200)
          ElMessage.success({
            message: "重置成功",
            center: true
          });
      });
    })
    .catch(() => {});
}
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 160px); margin: 10px">
      <search-bar>
        <el-form
          :model="data.search"
          size="default"
          label-width="auto"
          label-suffix=""
        >
          <el-row :gutter="30">
            <el-col :span="5">
              <el-form-item label="用户名称">
                <el-input
                  v-model="data.search.name"
                  placeholder="请输入用户名称"
                  clearable
                  @keydown.enter="currentChange()"
                  @clear="currentChange()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="所在部门">
                <el-tree-select
                  v-model="data.search.deptId"
                  :data="data.deptOptions"
                  :default-expand-all="true"
                  node-key="id"
                  @node-click="getnode"
                  :check-strictly="true"
                  placeholder="请选择所在部门"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item>
                <el-button type="primary" @click="currentChange()">
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:search" />
                    </el-icon>
                  </template>
                  查询
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </search-bar>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button-group>
            <el-button type="primary" @click="onAdd">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:circle-plus" />
                </el-icon>
              </template>
              新增
            </el-button>
            <el-button type="danger" @click="onDel">
              <template #icon>
                <el-icon>
                  <svg-icon name="ep:close-bold" :size="20" />
                </el-icon>
              </template>
              删除
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>
      <div style="height: calc(100vh - 380px); overflow-y: auto">
        <el-tabs
          v-model="activeName"
          class="demo-tabs"
          @tab-click="handleClick"
        >
          <el-tab-pane label="平台用户" name="first">
            <el-table
              ref="table"
              v-loading="data.loading"
              class="list-table"
              :data="data.dataList"
              border
              highlight-current-row
              row-key="id"
              @sort-change="sortChange"
              @selection-change="data.batch.selectionDataList = $event"
            >
              >
              <el-table-column type="selection" align="center" />
              <el-table-column prop="name" label="姓名" width="150">
                <template v-slot="scope">
                  <el-avatar
                    :style="{ backgroundColor: getRandomColor(scope.$index) }"
                    style="color: #fff; width: 32px; height: 32px"
                    shape="square"
                  >
                    {{ getShowName(scope.row.name) }}
                  </el-avatar>
                  &nbsp;{{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column prop="userName" label="登录账号" align="center">
              </el-table-column>
              <el-table-column
                prop="userType"
                label="用户类型"
                align="center"
                width="100"
              >
                <template v-slot="scope">
                  <el-tag v-if="scope.row.userType == '0'" effect="Light"
                    >平台</el-tag
                  >
                  <el-tag v-else effect="Light" type="warning">商户</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="phonenumber" label="手机号码" />
              <el-table-column
                prop="status"
                label="在职状态"
                width="90"
                align="center"
              >
                <template v-slot="scope">
                  <el-tag v-if="scope.row.status == '0'" effect="Light"
                    >在职</el-tag
                  >
                  <el-tag v-else effect="Light" type="warning">离职</el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="sysDept.deptName" label="所在部门" />
              <el-table-column prop="posts" label="在职岗位" />
              <el-table-column prop="roles" label="分配角色" />
              <el-table-column prop="createTime" label="入职时间">
                <template v-slot="scope">
                  {{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240" align="center">
                <template #default="scope">
                  <el-button-group>
                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="onEdit(scope.row)"
                    >
                      <template #icon>
                        <el-icon>
                          <svg-icon name="ant-design:edit-filled" />
                        </el-icon>
                      </template>
                      编 辑</el-button
                    >

                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="resetPwd(scope.row)"
                    >
                      <template #icon>
                        <el-icon>
                          <svg-icon name="ant-design:redo-outlined" />
                        </el-icon>
                      </template>
                      重置密码</el-button
                    ><el-button
                      type="danger"
                      text
                      size="small"
                      @click="onDel(scope.row)"
                    >
                      <template #icon>
                        <el-icon>
                          <svg-icon name="ep:close-bold" />
                        </el-icon>
                      </template>
                      删除
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table></el-tab-pane
          >
          <el-tab-pane label="商户用户" name="second">
            <el-table
              ref="table"
              v-loading="data.loading"
              class="list-table"
              :data="data.dataList"
              border
              highlight-current-row
              row-key="id"
              @sort-change="sortChange"
              @selection-change="data.batch.selectionDataList = $event"
            >
              >
              <el-table-column type="selection" align="center" />
              <el-table-column prop="name" label="姓名" width="150">
                <template v-slot="scope">
                  <el-avatar
                    :style="{ backgroundColor: getRandomColor(scope.$index) }"
                    style="color: #fff; width: 32px; height: 32px"
                    shape="square"
                  >
                    {{ getShowName(scope.row.name) }}
                  </el-avatar>
                  &nbsp;{{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column prop="userName" label="登录账号" align="center">
              </el-table-column>
              <el-table-column
                prop="userType"
                label="用户类型"
                align="center"
                width="100"
              >
                <template v-slot="scope">
                  <el-tag v-if="scope.row.userType == '0'" effect="Light"
                    >平台</el-tag
                  >
                  <el-tag v-else effect="Light" type="warning">商户</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="phonenumber" label="手机号码" />
              <el-table-column
                prop="status"
                label="在职状态"
                width="90"
                align="center"
              >
                <template v-slot="scope">
                  <el-tag v-if="scope.row.status == '0'" effect="Light"
                    >在职</el-tag
                  >
                  <el-tag v-else effect="Light" type="warning">离职</el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="sysDept.deptName" label="所在部门" />
              <el-table-column prop="posts" label="在职岗位" />
              <el-table-column prop="roles" label="分配角色" />
              <el-table-column prop="createTime" label="入职时间">
                <template v-slot="scope">
                  {{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240" align="center">
                <template #default="scope">
                  <el-button-group>
                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="onEdit(scope.row)"
                    >
                      <template #icon>
                        <el-icon>
                          <svg-icon name="ant-design:edit-filled" />
                        </el-icon>
                      </template>
                      编 辑</el-button
                    >

                    <el-button
                      type="primary"
                      size="small"
                      text
                      @click="resetPwd(scope.row)"
                    >
                      <template #icon>
                        <el-icon>
                          <svg-icon name="ant-design:redo-outlined" />
                        </el-icon>
                      </template>
                      重置密码</el-button
                    ><el-button
                      type="danger"
                      text
                      size="small"
                      @click="onDel(scope.row)"
                    >
                      <template #icon>
                        <el-icon>
                          <svg-icon name="ep:close-bold" />
                        </el-icon>
                      </template>
                      删除
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table></el-tab-pane
          >
        </el-tabs>
      </div>

      <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      :name="data.formModeProps.name"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
